import { logout, getMemberList } from '@/api/user';
import { getToken, setToken, removeToken } from '@/utils/auth';
import router, { resetRouter } from '@/router';

const SHULAN_SESSION_USER = 'shulan_sessionUser';
let info = localStorage.getItem(SHULAN_SESSION_USER);
info = info ? JSON.parse(info) : {};
const state = {
  token: getToken(),
  name: '',
  avatar: '',
  introduction: '',
  roles: [],
  sessionUser: info, // 用户信息
  staffInfo: {},
  vipStatus: '' // vip状态 0:正常 1:禁用 2:到期 3:非会员
};

const mutations = {
  SET_TOKEN: (state, token) => {
    state.token = token;
  },
  SET_INTRODUCTION: (state, introduction) => {
    state.introduction = introduction;
  },
  SET_NAME: (state, name) => {
    state.name = name;
  },
  SET_AVATAR: (state, avatar) => {
    state.avatar = avatar;
  },
  SET_ROLES: (state, roles) => {
    state.roles = roles;
  },
  SET_USER_INFO: (state, value) => {
    state.sessionUser = value;
  },
  SET_STAFF_INFO: (state, value) => {
    state.staffInfo = Object.assign({}, value);
  },
  SET_VIP_STATUS: (state, value) => {
    state.vipStatus = value;
  }
};

const actions = {
  userLogins({ commit }, response) {
    return new Promise((resolve, reject) => {
      const tokenCode = response.content.token;
      commit('SET_TOKEN', tokenCode);
      localStorage.setItem(SHULAN_SESSION_USER, JSON.stringify(response.content.sessionUser));
      commit('SET_USER_INFO', response.content.sessionUser);
      setToken(tokenCode);

      resolve();
    });
  },

  // user logout
  logout({ commit, state, dispatch }) {
    return new Promise((resolve, reject) => {
      logout(state.token)
        .then(() => {
          gio('clearUserId');
          commit('SET_TOKEN', '');
          // commit('SET_ROLES', [])
          removeToken();
          // resetRouter()

          // reset visited views and cached views
          // to fixed https://github.com/PanJiaChen/vue-element-admin/issues/2485
          dispatch('tagsView/delAllViews', null, { root: true });

          resolve();
        })
        .catch((error) => {
          reject(error);
        });
    });
  },

  // remove token
  // resetToken({ commit }) {
  //   return new Promise((resolve) => {
  //     commit('SET_TOKEN', '');
  //     commit('SET_ROLES', []);
  //     removeToken();
  //     resolve();
  //   });
  // },

  // dynamically modify permissions
  async changeRoles({ commit, dispatch }, role) {
    const token = role + '-token';

    commit('SET_TOKEN', token);
    setToken(token);

    const { roles } = await dispatch('getInfo');

    resetRouter();

    // generate accessible routes map based on roles
    const accessRoutes = await dispatch('permission/generateRoutes', roles, { root: true });
    // dynamically add accessible routes
    router.addRoutes(accessRoutes);

    // reset visited views and cached views
    dispatch('tagsView/delAllViews', null, { root: true });
  },

  setStaffInfo({ commit }, value) {
    commit('SET_STAFF_INFO', value);
  },

  // 加载用户vip状态
  loadUserVip({ commit, state }) {
    return new Promise(async (resolve, reject) => {
      try {
        const memberAgentId = state.sessionUser.id;
        if (!memberAgentId) {
          reject();
          return;
        }
        const res = await getMemberList({
          currentPage: 1,
          pageSize: 1,
          t: {
            memberAgentId: memberAgentId
          }
        });
        if (res && res.isSuccess && res.content) {
          let vip = res.content.statue || '';
          commit('SET_VIP_STATUS', vip);
          resolve(vip);
        } else {
          reject();
        }
      } catch (error) {
        reject();
      }
    });
  }
};

export default {
  state,
  mutations,
  actions,
  getters: {}
};
